<template>
  <div class="app-container">
    <!--  1-搜索框    -->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">

        <!--条件框1、根据状态筛选-->
        <el-form-item>
          <el-select v-model="value" @change="chickYear" clearable placeholder="年份">
            <el-option
              v-for="item in status"
              :key="item.statusId"
              :label="item.label"
              :value="item.statusId">
            </el-option>
          </el-select>
        </el-form-item>

<!--        &lt;!&ndash;条件框2、根据命名筛选&ndash;&gt;-->
<!--        <el-form-item>-->
<!--          <el-input   placeholder="名称" v-model="searchName"></el-input>-->
<!--        </el-form-item>-->

        <!--“搜索”按钮-->
        <el-form-item>
          <el-button type="primary" @click="doFilter()"><i class="el-icon-search"></i>搜索</el-button>
        </el-form-item>

        <!--“新增”按钮-->
        <el-form-item>
          <el-button type="primary" @click="addUpdate()">新增</el-button>
        </el-form-item>

      </el-form>
    </el-col>

    <div>

      <div style="float:left; width: 50%;">
        <viewer :span="6" style="width: 100%;height: 100%">

          <!--<img :src="this.GLOBAL.shot.imgUrl" style="max-width: 90%; max-height: 100%; width: 2000px">-->
          <img :src="this.bigfarmImgUrl" style="max-width: 60%; max-height: 60%; width: 1200px">

        </viewer>
      </div>

      <div style="float:right; width: 50%;">

        <!-- 2-列表              -->
        <el-table :data="tableList" max-height="450" v-loading="listLoading" border element-loading-text="拼命加载中" style="width: 100%;">

          <el-table-column prop="id" label="试验田ID" >
          </el-table-column>
          <el-table-column prop="name" label="试验名称">
          </el-table-column>
          <el-table-column prop="num" label="试验品种数量">
          </el-table-column>

          <el-table-column prop="operation" label="操作 ">
            <template slot-scope="scope">

<!--              <el-button size="small" type="primary" @click="editFarms(scope.row)">规划</el-button>-->

              <el-button size="mini" type="success" @click="getInShotList(scope.row)">进入</el-button>

              <!--          <el-button size="small" type="danger" @click="deleteUpdate(scope.row)">删除</el-button>-->



            </template>
          </el-table-column>

        </el-table>


        <!--  3-分页插件的工具条                 -->
        <el-pagination layout="total, prev, pager, next"
                       background
                       :page-size="10"
                       @size-change="handleSizeChange"
                       :total="total"
                       @current-change="handleCurrentChange"
                       style="text-align:center;">
        </el-pagination>
      </div>
    </div>

    <!-- 5-新增Farmland弹窗详情 -->
    <el-dialog title="Edit1" :visible.sync="isShowAddVisible">

      <el-form label-width="80px" :model="fieldMSg" ref="dataForm">
        <el-form-item label="试验ID" prop="fname">
          <el-input v-model="fieldMSg.id"></el-input>
        </el-form-item>
      </el-form>

      <el-form label-width="80px" :model="fieldMSg" ref="dataForm">
        <el-form-item label="试验类型" prop="fname">
          <el-input v-model="fieldMSg.name"></el-input>
        </el-form-item>
      </el-form>

      <el-form label-width="80px" :model="fieldMSg" ref="dataForm">
        <el-form-item label="试验品种数" prop="fname">
          <el-input v-model="fieldMSg.num"></el-input>
        </el-form-item>
      </el-form>

      <el-form label-width="80px" :model="fieldMSg" ref="dataForm">
        <el-form-item label="类型">
          <el-switch
            v-model="fieldMSg.type"
            active-text="greenhouse"
            inactive-text="common"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :disabled="editStatus">
          </el-switch>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="isShowAddVisible = false">取消</el-button>
        <el-button type="primary" :loading="listLoading" @click="updateData1(farmMsg)" class="title1">确定</el-button>
      </div>

    </el-dialog>

    <!-- 6-删除试验田弹框                           -->
    <el-dialog
      title="删除"
      :visible.sync="deleteVisible"
      width="30%">
      <span>确认删除吗</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitDelete">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>


<script>
  import { addFarm,getFarmList,deleteFarm,updateFarm,getFarmListByBigfarmId } from '../../api/FarmManager'
  import { getFarms } from '../../api/BigFarmManage'
  //import { getGreenhouses } from '../../api/BigFarmManage'
  import { getFieldPlan,getBigfarmByYear} from '../../api/BigFarmManage'

  export default {

    data() {
      return {
        tableList: [],
        listLoading: true,
        isShowEditVisible: false,
        isShowAddVisible: false,
        deleteVisible: false,
        temp: {
          uid: '',
          cname: '',
          date: '',
          status: ''
        },
        farmMsg: {
          name: '',
          length: '',
          width: '',
          type: ''
        },

        fieldMSg: {
          name: '',
          id: '',
          num: '',
          type: ''
        },
        total: 0,
        page: 1,
        pageSize: 10,
        farmlandId: '',
        currentYear: '2003',
        currentBigfarmId: 'bigfarm15648395185921422',
        status: [
          {
            statusId: 2005,
            label: '2005年'
          }, {
            statusId: 2004,
            label: '2004年'
          },{
            statusId: 2003,
            label: '2003年'
          },{
            statusId: 1999,
            label: '1999年'
          }

        ],

        value: '',
        searchName: '',
        filterTableDataEnd: [],
        bigfarmImgUrl: '',
        screenWidth: document.body.clientWidth,
      }
    },

    mounted() {
      // 1、数据首次加载完后 → 获取图片（或外层框）宽度，并设置其高度
      this.$nextTick(() => {
        // 获取图片（或外层框）
        let imgBox = this.$refs.imgBox
        // 获取其宽度
        let wImgbox = imgBox[0].getBoundingClientRect().width
        // 设置其高度（以宽度的60%为例）
        this.imgBox.height = 0.6 * wImgbox + 'px'
      })
      // 2、挂载 reisze 事件 → 屏幕缩放时监听宽度变化
      const that = this
      window.onresize = () => {
        return (() => {
          window.screenWidth = document.body.clientWidth
          that.screenWidth = window.screenWidth
          console.log(that.screenWidth)
          this.$nextTick(() => {
            let imgBox = this.$refs.imgBox
            let wImgbox = imgBox[0].getBoundingClientRect().width
            this.imgBox.height = 0.6 * wImgbox + 'px'
          })
        })()
      }
    },
    watch: {
      screenWidth(val) {

        if (!this.timer) {
          this.screenWidth = val
          this.timer = true
          let that = this
          setTimeout(function() {
            console.log("自适应" + that.screenWidth)
            that.timer = false
          }, 400)
        }
      }
    },

    created() {
      // 刚打开页面时就去取数据；
      this.fetchData()
    },

    filters: {
      statusFilter(status) {
        const statusMap = {
          1: 'success',
          2: 'danger'
        }
        return statusMap[status]
      }
    },

    methods: {
      // 新增farmland更新数据
      updateData1(farmMsg) {
        this.listLoading = true
        addFarm({
          'name': farmMsg.farmName, 'length': farmMsg.length, 'width': farmMsg.width,
          'bigfarmId': this.GLOBAL.bigfarmId, 'type': farmMsg.type
        }).then(response => {
          this.fetchData()
        })
        this.isShowAddVisible = false
        this.$notify({
          title: '成功',
          message: '添加成功',
          type: 'success',
          duration: 2000
        })
      },

      getInShotList(farmland) {
        this.GLOBAL.fieldId = farmland.id
        this.$router.push('/plantDesign')
        // if (farmland.type === 'common') {
        //   this.$router.push('/browser')
        // } else {
        //   this.$router.push('/greenhouseDesign')
        // }
      },

      fetchData() {
        this.listLoading = true
        //var tableList = []

        getBigfarmByYear(this.currentYear).then(response => {
          this.currentBigfarmId = response.data.rows[0].id

          this.bigfarmImgUrl = 'http://cxk.nicesite.vip/' + response.data.rows[0].img
        })
        getFieldPlan(this.currentBigfarmId).then(response => {
          console.log('OOOOO' + this.currentBigfarmId)
          // 居然在前端做筛选，牛逼！
          this.tableList = response.data.rows //.filter((item, index) => index < limit * this.page && index >= limit * (this.page - 1))
          // console.log(pageList)
          this.total = response.data.total
        })

          //console.log(pageList)
          //console.log('大田图片地址是：' + this.GLOBAL.bigfarmImgUrl)
          //console.log('farm列表是：' + this.GLOBAL.bigfarmId)
          //console.log('111111+ ' + tableList[0].name)
          this.listLoading = false

          // getGreenhouses("bigfarm15628287025057066").then(res => {
          //   const limit = 10
          //   console.log('222222+ ' + pageList.length)
          //   for (var i = 0; i < res.data.rows.length; i++) {
          //     var obj = res.data.rows[i]
          //     obj['type'] = 'greenhouse'
          //     obj['farmlandId'] = obj['id']
          //     pageList.push(obj)
          //   }
          //   pageList.filter((item, index) => index < limit * this.page && index >= limit * (this.page - 1))
          //   this.total = pageList.length
          //   this.tableList = pageList
          //   //this.bigfarmImgUrl = 'http://cxk.nicesite.vip/' + response.data.data.img
          //   console.log(pageList)
          //
          //   console.log('333333+ ' + pageList.length)
          //   this.listLoading = false
          // })
        // getGreenhouses(this.GLOBAL.bigfarmId).then(res => {
        //   const limit = 10
        //   console.log('222222+ ' + pageList.length)
        //   for (var i = 0; i < res.data.rows.length; i++) {
        //     var obj = res.data.rows[i]
        //     obj['type'] = 'greenhouse'
        //     pageList.push(obj)
        //   }
        //   pageList.filter((item, index) => index < limit * this.page && index >= limit * (this.page - 1))
        //   this.total = pageList.length
        //   this.tableList = pageList
        //   //this.bigfarmImgUrl = 'http://cxk.nicesite.vip/' + response.data.data.img
        //   console.log(pageList)
        //
        //   console.log('333333+ ' + pageList.length)
        //   this.listLoading = false
        // })
      },

      doFilter() {
        console.log(this.searchName)

        //this.listLoading = true
        this.currentYear = this.value
        console.log('EEEE' + this.currentYear)
        getBigfarmByYear(this.currentYear).then(response => {
          this.currentBigfarmId = response.data.rows[0].id

          this.bigfarmImgUrl = 'http://cxk.nicesite.vip/' + response.data.rows[0].img
          console.log('3333' + this.bigfarmImgUrl)

        })
        getFieldPlan(this.currentBigfarmId).then(response => {
          // 居然在前端做筛选，牛逼！
          this.tableList = response.data.rows //.filter((item, index) => index < limit * this.page && index >= limit * (this.page - 1))
          // console.log(pageList)
          this.total = response.data.total
        })
        //this.listLoading = false
      },
      chickYear() {
        console.log('FFF' + this.value)
      },

      clickfun(e) {
        console.log(e.target.innerText)
      },

      handleUpdate(row) {
        this.isShowEditVisible = true
        this.temp = Object.assign({}, row)
        console.log(row)
      },


      deleteUpdate(row) {
        console.log(row)
        this.deleteVisible = true
        this.temp = Object.assign({}, row)
        this.farmlandId = row.farmlandId
      },

      editFarms(row) {
        // this.GLOBAL.farmland = farmland
        // console.log(farmland)

        if ( row.type === 'common') {
          console.log("tttttt+"+row.type)
          window.open('src/editor/grid-css.html?farmlandId=' + row.farmlandId)
        } else {
          this.GLOBAL.farmland.farmlandId = row.farmlandId
          this.$router.push('/greenhouseDesign')
        }
      },

      submitDelete() {
        const tempData = Object.assign({}, this.temp)
        console.log(tempData)
        console.log(this.tableList)
        for (const v of this.tableList) {
          if (v.uid === this.temp.uid) {
            const index = this.tableList.indexOf(v)
            this.tableList.splice(index, 1)
            this.fetchData()
            console.log(this.tableList)
            break
          }
        }
        deleteFarm({ 'farmlandId': this.farmlandId }).then(response => {
          this.fetchData()
        })

        this.deleteVisible = false
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
      },

      handleModifyStatus(row, status) {
        this.$message({
          message: '操作成功',
          type: 'success'
        })
        console.log(row)
        row.status = status
      },

      updateData() {
        const tempData = Object.assign({}, this.temp)
        console.log(tempData)
        updateArticle(tempData).then(() => {
          for (const v of this.tableList) {
            if (v.uid === this.temp.uid) {
              const index = this.tableList.indexOf(v)
              this.tableList.splice(index, 1, this.temp)
              break
            }
          }
          this.isShowEditVisible = false
          this.$notify({
            title: '成功',
            message: '更新成功',
            type: 'success',
            duration: 2000
          })
        })
      },

      handleSizeChange(val) {
        this.page = val
        console.log(this.page)
        this.fetchData()
      },

      handleCurrentChange(val) {
        this.page = val
        console.log(this.page)
        this.fetchData()
      },

      currentChangePage(list) {
        let from = (this.page - 1) * this.pageSize
        const to = this.page * this.pageSize
        this.tableList = []
        for (; from < to; from++) {
          if (list[from]) {
            this.tableList.push(list[from])
          }
        }
      }
    }
  }
</script>

